package main

import (
	"log"
	"net"
	"net/http"
	"os"
	"strings"
)

func index(w http.ResponseWriter, r *http.Request) {
	// 获取请求 Header 并设置响应 Header
	headers := r.Header
	for key, values := range headers {
		for _, v := range values {
			w.Header().Add(key, v)
		}
	}

	// 获取环境变量VERSION
	verKey := "VERSION"
	version := os.Getenv(verKey)
	if version == "" {
		os.Setenv(verKey, "v1.0.0")
		version = os.Getenv(verKey)
	}

	// 设置VERSION Header
	w.Header().Add(verKey, version)

	// 获取客户端 IP
	ip := getClientIp(r)

	// 记录日志
	log.Println(ip)
	log.Println(http.StatusOK)

	// 输出
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(ip))
}

func getClientIp(r *http.Request) string {
	clientIP := strings.TrimSpace(string(r.Header.Get("X-Forwarded-For")))

	if index := strings.IndexByte(clientIP, ','); index >= 0 {
		if ip := clientIP[0:index]; len(ip) > 0 {
			return ip
		}
	}

	if ip := strings.TrimSpace(string(r.Header.Get("X-Real-Ip"))); len(ip) > 0 {
		return ip
	}

	if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
		return ip
	}

	return ""
}

func healthz(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("OK"))
}

func main() {
	http.HandleFunc("/", index)
	http.HandleFunc("/healthz", healthz)

	log.Fatal(http.ListenAndServe(":8080", nil))
}
